# -*- coding:utf-8 -*-
'''
# Author: xiguan
# Mail: xiguan.teng@qq.com
# -----
# Last Modified: 2022-05-11 16:37:17
# Modified By: xiguan
# -----
# Copyright (c) 2022 XiGuan Inc.
# 
# No Bug No error No warning.
# -----
'''
import json
from pickle import loads

from flask import Blueprint, session, request

from config import db_session, engine
# from pojo.log import Log
from entity.Log import Log

log = Blueprint('log',__name__)

# 将日志对象转化为 json 格式
def log_2_json(obj):
   return {
        "id": obj.id,
        "uid": obj.uid,
        "username": obj.username,
        "syncdir_id": obj.syncdir_id,
        "syncdir_path": obj.syncdir_path,
        "direction": obj.direction,
        "sync_time": obj.sync_time,
        "server_port": obj.server_port
   }

@log.route("/get_all_synclog/")
def get_all_synclog():
    try:
        user = loads(session.get("user"))
        logs = list(db_session.query(Log).filter_by(uid=user.id).order_by("sync_time"))
    except Exception:
        return {"status": "NO"}
    return {"status":"OK", "logs": json.dumps(logs, default=log_2_json)}

# 删除指定日志
@log.route("/del_log/")
def del_log():
    id = request.args.get("id")
    del_log = list(db_session.query(Log).filter_by(id=id))[0]
    db_session.delete(del_log)
    db_session.commit()
    return "OK"

# 清空日志
@log.route("/clear_log/")
def clear_log():
    try:
        user = loads(session.get("user"))
        with engine.connect() as con:
            execute_string = "delete from miniftp_test.log where uid = " + str(user.id)
            con.execute(execute_string)
            db_session.commit()
    except Exception:
        return "NO"
    return "OK"